'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Users, BookOpen, BarChart3, Settings, Shield, Database, Activity, AlertTriangle } from 'lucide-react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'

interface SystemStats {
  totalUsers: number
  activeUsers: number
  totalQuestions: number
  totalTopics: number
  totalSessions: number
  averageAccuracy: number
  systemHealth: 'good' | 'warning' | 'error'
  lastBackup: string
}

interface RecentActivity {
  id: string
  type: 'user_register' | 'question_added' | 'session_completed' | 'system_error'
  description: string
  timestamp: string
  severity: 'info' | 'warning' | 'error'
}

export default function AdminDashboard() {
  const [stats, setStats] = useState<SystemStats | null>(null)
  const [recentActivity, setRecentActivity] = useState<RecentActivity[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')

  // 模拟系统统计数据
  const mockStats: SystemStats = {
    totalUsers: 1247,
    activeUsers: 342,
    totalQuestions: 856,
    totalTopics: 60,
    totalSessions: 5432,
    averageAccuracy: 78.5,
    systemHealth: 'good',
    lastBackup: '2025-09-24T02:00:00Z'
  }

  // 模拟最近活动
  const mockActivity: RecentActivity[] = [
    {
      id: '1',
      type: 'user_register',
      description: '新用户 "张小明" 注册成功',
      timestamp: '2025-09-24T10:30:00Z',
      severity: 'info'
    },
    {
      id: '2',
      type: 'session_completed',
      description: '用户完成每日练习，正确率 92%',
      timestamp: '2025-09-24T10:15:00Z',
      severity: 'info'
    },
    {
      id: '3',
      type: 'question_added',
      description: '管理员添加了 5 道新题目',
      timestamp: '2025-09-24T09:45:00Z',
      severity: 'info'
    },
    {
      id: '4',
      type: 'system_error',
      description: '数据库连接超时，已自动恢复',
      timestamp: '2025-09-24T08:20:00Z',
      severity: 'warning'
    }
  ]

  useEffect(() => {
    loadDashboardData()
  }, [])

  const loadDashboardData = async () => {
    try {
      setIsLoading(true)

      // 直接从数据库加载真实数据
      await Promise.all([
        loadSystemStats(),
        loadRecentActivity()
      ])
    } catch (err) {
      console.error('加载管理员数据错误:', err)
      setError('加载管理员数据时发生错误')
      // 如果加载失败，使用模拟数据作为后备
      setStats(mockStats)
      setRecentActivity(mockActivity)
    } finally {
      setIsLoading(false)
    }
  }

  const loadSystemStats = async () => {
    try {
      console.log('🔄 开始加载统计数据...')

      // 调用API获取真实统计数据
      const response = await fetch('/api/admin/stats', {
        credentials: 'include'
      })

      console.log('📡 API响应状态:', response.status)

      if (response.ok) {
        const data = await response.json()
        console.log('📊 API返回数据:', data)

        if (data.success) {
          console.log('✅ 统计数据加载成功:', data.data)
          setStats(data.data)
        } else {
          console.error('❌ 获取统计数据失败:', data.error)
          setStats(mockStats)
        }
      } else {
        const errorText = await response.text()
        console.error('❌ API请求失败:', response.status, errorText)
        setStats(mockStats)
      }
    } catch (error) {
      console.error('❌ 加载统计数据错误:', error)
      setStats(mockStats)
    }
  }

  const loadRecentActivity = async () => {
    try {
      console.log('🔄 开始加载活动数据...')

      // 调用API获取最近活动
      const response = await fetch('/api/admin/activity', {
        credentials: 'include'
      })

      console.log('📡 活动API响应状态:', response.status)

      if (response.ok) {
        const data = await response.json()
        console.log('📊 活动API返回数据:', data)

        if (data.success) {
          console.log('✅ 活动数据加载成功:', data.data)
          setRecentActivity(data.data)
        } else {
          console.error('❌ 获取活动数据失败:', data.error)
          setRecentActivity([])
        }
      } else {
        const errorText = await response.text()
        console.error('❌ 活动API请求失败:', response.status, errorText)
        setRecentActivity([])
      }
    } catch (error) {
      console.error('❌ 加载活动数据错误:', error)
      setRecentActivity([])
    }
  }

  const getHealthColor = (health: string) => {
    switch (health) {
      case 'good': return 'text-green-600'
      case 'warning': return 'text-yellow-600'
      case 'error': return 'text-red-600'
      default: return 'text-gray-600'
    }
  }

  const getHealthLabel = (health: string) => {
    switch (health) {
      case 'good': return '良好'
      case 'warning': return '警告'
      case 'error': return '错误'
      default: return '未知'
    }
  }

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'info': return 'text-blue-600'
      case 'warning': return 'text-yellow-600'
      case 'error': return 'text-red-600'
      default: return 'text-gray-600'
    }
  }

  const getActivityIcon = (type: string) => {
    switch (type) {
      case 'user_register': return Users
      case 'question_added': return BookOpen
      case 'session_completed': return BarChart3
      case 'system_error': return AlertTriangle
      default: return Activity
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN')
  }

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载管理员面板中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8"
        >
          <h1 className="text-3xl font-bold text-gray-800 dark:text-gray-200 mb-2">
            管理员面板
          </h1>
          <p className="text-gray-600 dark:text-gray-300">
            系统管理和监控中心
          </p>
        </motion.div>

        {/* 错误提示 */}
        {error && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 p-4 rounded-lg bg-red-100 border border-red-300 text-red-700"
          >
            {error}
          </motion.div>
        )}

        {/* 系统统计 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="grid grid-cols-2 md:grid-cols-4 gap-6 mb-8"
        >
          {stats && [
            {
              title: '总用户数',
              value: stats.totalUsers.toLocaleString(),
              icon: Users,
              color: 'text-blue-600'
            },
            {
              title: '活跃用户',
              value: stats.activeUsers.toLocaleString(),
              icon: Activity,
              color: 'text-green-600'
            },
            {
              title: '题目总数',
              value: stats.totalQuestions.toLocaleString(),
              icon: BookOpen,
              color: 'text-purple-600'
            },
            {
              title: '知识点数',
              value: stats.totalTopics.toString(),
              icon: Database,
              color: 'text-orange-600'
            }
          ].map((stat, index) => (
            <Card key={stat.title} glassmorphism className="backdrop-blur-xl">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600 mb-1">{stat.title}</p>
                    <p className={`text-2xl font-bold ${stat.color}`}>{stat.value}</p>
                  </div>
                  <stat.icon className={`w-8 h-8 ${stat.color}`} />
                </div>
              </CardContent>
            </Card>
          ))}
        </motion.div>

        <div className="grid lg:grid-cols-3 gap-6">
          {/* 快速操作 */}
          <motion.div
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.2 }}
            className="lg:col-span-1"
          >
            <Card glassmorphism className="backdrop-blur-xl">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Settings className="w-5 h-5" />
                  快速操作
                </CardTitle>
                <CardDescription>
                  常用管理功能
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-3">
                <Link href="/admin/users">
                  <Button variant="outline" className="w-full justify-start">
                    <Users className="w-4 h-4 mr-2" />
                    用户管理
                  </Button>
                </Link>
                <Link href="/admin/questions">
                  <Button variant="outline" className="w-full justify-start">
                    <BookOpen className="w-4 h-4 mr-2" />
                    题库管理
                  </Button>
                </Link>
                <Link href="/admin/topics">
                  <Button variant="outline" className="w-full justify-start">
                    <Database className="w-4 h-4 mr-2" />
                    知识点管理
                  </Button>
                </Link>
                <Link href="/admin/question-review">
                  <Button variant="outline" className="w-full justify-start">
                    <Shield className="w-4 h-4 mr-2" />
                    题库检测
                  </Button>
                </Link>
                <Link href="/admin/analytics">
                  <Button variant="outline" className="w-full justify-start">
                    <BarChart3 className="w-4 h-4 mr-2" />
                    数据分析
                  </Button>
                </Link>
                <Link href="/admin/settings">
                  <Button variant="outline" className="w-full justify-start">
                    <Settings className="w-4 h-4 mr-2" />
                    系统设置
                  </Button>
                </Link>
              </CardContent>
            </Card>
          </motion.div>

          {/* 系统状态和最近活动 */}
          <div className="lg:col-span-2 space-y-6">
            {/* 系统状态 */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.3 }}
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Shield className="w-5 h-5" />
                    系统状态
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  {stats && (
                    <div className="grid grid-cols-2 gap-6">
                      <div className="space-y-4">
                        <div className="flex items-center justify-between">
                          <span className="text-gray-600">系统健康度</span>
                          <span className={`font-medium ${getHealthColor(stats.systemHealth)}`}>
                            {getHealthLabel(stats.systemHealth)}
                          </span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-gray-600">总练习次数</span>
                          <span className="font-medium">{stats.totalSessions.toLocaleString()}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-gray-600">平均正确率</span>
                          <span className="font-medium text-blue-600">{stats.averageAccuracy}%</span>
                        </div>
                      </div>
                      <div className="space-y-4">
                        <div className="flex items-center justify-between">
                          <span className="text-gray-600">最后备份</span>
                          <span className="font-medium text-sm">
                            {formatDate(stats.lastBackup)}
                          </span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-gray-600">用户活跃度</span>
                          <span className="font-medium text-green-600">
                            {Math.round((stats.activeUsers / stats.totalUsers) * 100)}%
                          </span>
                        </div>
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            </motion.div>

            {/* 最近活动 */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.4 }}
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Activity className="w-5 h-5" />
                    最近活动
                  </CardTitle>
                  <CardDescription>
                    系统最新动态和事件
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {recentActivity.map(activity => {
                      const IconComponent = getActivityIcon(activity.type)
                      return (
                        <div key={activity.id} className="flex items-start gap-3 p-3 rounded-lg bg-white/50">
                          <IconComponent className={`w-5 h-5 mt-0.5 ${getSeverityColor(activity.severity)}`} />
                          <div className="flex-1">
                            <p className="text-sm text-gray-800">{activity.description}</p>
                            <p className="text-xs text-gray-500 mt-1">
                              {formatDate(activity.timestamp)}
                            </p>
                          </div>
                        </div>
                      )
                    })}
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>
        </div>

        {/* 系统监控图表区域 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.5 }}
          className="mt-8"
        >
          <Card glassmorphism className="backdrop-blur-xl">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <BarChart3 className="w-5 h-5" />
                系统监控
              </CardTitle>
              <CardDescription>
                实时系统性能和使用情况
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="h-64 flex items-center justify-center text-gray-500">
                <div className="text-center">
                  <BarChart3 className="w-16 h-16 mx-auto mb-4 text-gray-400" />
                  <p>监控图表功能开发中...</p>
                  <p className="text-sm mt-2">将显示用户活动、系统性能等实时数据</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </motion.div>
      </div>
    </div>
  )
}
